﻿using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using SCM.API.Read.Application.Command.Sale;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Sale
{
    public class GetSaleOneHandler : IRequestHandler<GetSaleOneCommand, APIResult<SaleManagementModel>>
    {
        IDatabaseContext db;

        public GetSaleOneHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<SaleManagementModel>> Handle(GetSaleOneCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<SaleManagementModel>();

            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT 
                                        id,
                                        SaleId,
                                        ProductName,
                                        productId,
                                        productSpecs,
                                        unitId,
                                        price,        
                                        num,
                                        total,
                                        customerId,
                                        customerName,
                                        ContactPerson,
                                        Phone,
                                        Description,
                                        state,
                                        recorded,
                                        refundNum,
                                        madeName,
                                        madeTime,
                                        createTime,
                                        updateName,
                                        createName,
                                        isDel
                                FROM SaleManagementModel WHERE IsDel=0 ");

            var parameters = new DynamicParameters();

            if (request.Id != null)
            {
                sqlBuilder.Append("AND Id = @Id ");
                parameters.Add("Id", request.Id);

            }

           

            var data = await db.DapperConnection.QueryAsync<SaleManagementModel>(sqlBuilder.ToString(), parameters);

            result.Msg = "显示成功";
            result.Code = APIEnum.Success;
            result.Data = data.First();

            return result;
        }
    }
}
